﻿using System;
using System.Linq;
using Sales.Properties;

namespace Sales
{
    class Sections
    {
        private static Section _item = Items[0];
        public static Section Item
        {
            get { return _item; }
            set
            {
                if (_item == value) return;
                if (!Items.Contains(value))
                {
                    throw new Exception("値が不正です");
                }
                _item = value;
            }
        }

        private static Section[] _items;
        public static Section[] Items
        {
            get { return _items ?? (_items = CreateItems()); }
        }

        private static Section[] CreateItems()
        {
            var recordes = GetRecords();
            char[] separator = {':'};

            if (recordes.Select(record => record.Split(separator)).Any(c => c.Length != 2))
            {
                throw new Exception("セクションの指定が間違っています");
            }

            return
                recordes.Select(record => record.Split(separator))
                    .Select(c => new Section{Id = byte.Parse(c[0]), Title = c[1]})
                    .ToArray();
        }

        private static string[] GetRecords()
        {
            var records = Settings.Default.Sections.Split('|');
            return records;
        }
    }
}
